@extends('wx.layout.default')

@section('wx.pheader')
  @include('wx.layout.swiper')
@stop

@section('wx.pbody')

<form class="form-horizontal" id="wx-clase" autocomplete="off" enctype="multipart/form-data">
  <div class="weui-form">
    <div class="weui-form__text-area">
      <h2 class="weui-form__title">{{$tuser->clase->name}}公告</h2>
      <div class="weui-form__desc" style="text-align: left;font-size: 16px;">
        {{$tuser->clase->memo}}
      </div>
    </div>
    <div class="weui-form__control-area">

      {{ csrf_field() }}
      <input type="hidden" name="uid" value="{{$user->id}}"/>
      <input type="hidden" name="tuser" value="{{$tuser->id}}"/>

        <div class="weui-cells__group weui-cells__group_form">
          <div class="weui-cells__title b">
            {{ $tuser->term->name}} ({{ $tuser->branch->name}})
          </div>
          <div class="weui-cells weui-cells_radio deploys">
            <label class="weui-cell weui-cell_active weui-check__label" for="clase{{$tuser->clase->id}}">
                <div class="weui-cell__bd">
                    <p>【{{$tuser->clase->category->name}}】{{$tuser->clase->name}}</p>
                    <ul class="weui-media-box__info">
                        @if($tuser->clase->is_exam)
                        <li class="weui-media-box__info__meta"><span class="weui-badge" style="border-radius: 4px;background-color: var(--weui-FG-1)">{!! $tuser->clase->present()->isExam('label') !!}</span></li>
                        @endif

                        @if($tuser->clase->is_limited)
                        <li class="weui-media-box__info__meta"><span class="weui-badge" style="border-radius: 4px;background-color: var(--weui-FG-1)">{!! $tuser->clase->present()->isLimited('label') !!}</span>　<span style="float:right;color:var(--weui-FG-1);"> 已报名:<span style="color:var(--weui-BRAND);font-weight: 700">{{count($tuser->clase->enrolled)}}</span>  剩余:<span style="color:var(--weui-RED);font-weight: 700">{{$tuser->clase->number-count($tuser->clase->enrolled)}}</span></span></li>
                        @endif

                        @if($tuser->clase->is_handin)
                        <li class="weui-media-box__info__meta"><span class="weui-badge" style="border-radius: 4px;background-color: var(--weui-FG-1)">{!! $tuser->clase->present()->isHandin('label') !!}</span></li>
                        @endif
                    </ul>
                    <p class="weui-media-box__desc" style="-webkit-line-clamp: 6 !important;">{{$tuser->clase->content}}</p>
                    <p class="weui-media-box__desc" style="color:var(--weui-ORANGE)">上课时间：{{$tuser->clase->classtime}}</p>
                </div>
                <div class="enrol-status"><img src="/assets/images/clase{{$tuser->status}}.fw.png" /></div>
            </label>
          </div>

        </div>

      @if ($tuser->clase->is_handin)
        @if($tuser->status == 1)
          <div class="weui-cell weui-cell_uploader uploader">
              <div class="weui-cell__bd">
                  <div class="weui-uploader">
                      <div class="weui-uploader__hd">
                          <p class="weui-uploader__title">附件上传</p>
                          <div class="weui-uploader__info"><span id="uploadCount">{{count($tuser->attachments)}}</span>/4</div>
                      </div>
                      <div class="weui-uploader__bd">
                          <ul class="weui-uploader__files" id="uploaderFiles">
                            @foreach($tuser->attachments as $att)
                            <li class="weui-uploader__file" data-attid="{{$att->id}}" style="background-image: url({{$att->file}})"></li>
                            @endforeach
                          </ul>
                          <div class="weui-uploader__input-box">
                              <input class="weui-uploader__input" id="uploaderInput" name="files" type="file" accept="image/*" multiple="multiple">
                          </div>
                      </div>
                  </div>
              </div>
          </div>


          <div class="weui-gallery" id="gallery">
            <span class="weui-gallery__img" id="galleryImg"></span>
            <div class="weui-gallery__opr">
                <a href="javascript:" class="weui-gallery__del">
                    <i class="weui-icon-delete weui-icon_gallery-delete"></i>
                </a>
            </div>
          </div>

          @else
            <div class="weui-cell weui-cell_uploader uploader">
              <div class="weui-cell__bd">
                  <div class="weui-uploader">
                      <div class="weui-uploader__hd">
                          <p class="weui-uploader__title">已上传的附件</p>
                          <div class="weui-uploader__info"><span id="uploadCount">{{count($tuser->attachments)}}</span>/4</div>
                      </div>
                      <div class="weui-uploader__bd">
                          <ul class="weui-uploader__files" id="uploaderFiles">
                            @foreach($tuser->attachments as $att)
                            <li class="weui-uploader__file" data-attid="{{$att->id}}" style="background-image: url({{$att->file}})"></li>
                            @endforeach
                          </ul>
                      </div>
                  </div>
              </div>
            </div>
          @endif
      @endif

    </div>

    <div class="weui-form__opr-area">
      @if($tuser->clase->is_handin == 1 && $tuser->status == 1)
        <button class="weui-btn weui-btn_primary" id="btnDeploy">作品/证书上传</button>
      @endif
      @if( isset($tuser->clase->deploy) && $tuser->clase->deploy->status == 1)
      <button type="button" class="weui-btn weui-btn_warn" id="btnCancel">取消报名</button>
      @endif
    </div>
  </div>

</form>


@stop

@section('javascript')
  <script src="//cdn.bootcss.com/jquery-validate/1.19.1/jquery.validate.min.js"></script>
  <script src="{{URL::asset('/assets/js/jquery-validate-methods.js')}}"></script>
  <script src="//cdn.bootcss.com/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <script src="//cdn.bootcss.com/jquery-weui/1.2.1/js/swiper.min.js"></script>
  <script type="text/javascript" src="//res.wx.qq.com/open/libs/weuijs/1.2.1/weui.min.js"></script>
  <script type="text/javascript">


  $(function () {



      $("#wx-clase").validate({
          onfocusout: false,
          onkeyup: false,
          rules: {
              c: {required: true},
          },
          messages: {
              uploaderInput: {required: "请上传作品或公益证书"},
          },

          showErrors: function (errorMap, errorList) {
              $.each(errorList, function (i, v) {
                  layer.msg(v.message, {shift: -1, time: 2000});
                  return false;
              });
          },

          submitHandler: function (form) {

              var formData = new FormData();
              formData.append('_token', $("input[name='_token']").attr('value') );
              formData.append('tuser', $("input[name='tuser']").val() );
              formData.append('source', 1 );
              for (var i = 0; i < uploadFileList.length; i++){
                formData.append("files[]",uploadFileList[i])
              }

              $.ajax({
                type: "post",
                dataType: 'json',
                url: "{{route('wx.my.attachment.add')}}",
                data: formData,
                processData: false,
                contentType: false,
                success: function(data) {
                  console.log(data)
                  layer.msg(data.message, {time: 1500,shift: -1}, function () {
                      if (data.status === true && data.url != null) {
                        $(window).attr('location', data.url);
                      }
                  });
                },
                error: function (data) {
                    layer.msg(data.responseJSON.message);
                }
              });

          }

      });

      var uploadFileList = [];

      var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
      var maxSize = 1024 * 1024*10; // 10240KB，也就是 10MB
      var maxWidth = 1900;  // 图片最大宽度
      var maxCount = 4;// 最大上传图片数量
      var tmpl = '<li class="weui-uploader__file weui-uploader__file_status" id="#ImgID#" style="background-image:url(#url#)"><div class="weui-uploader__file-content"><i class="weui-loading" style="width:30px;height:30px"></i></div></li>',
          $gallery = $("#gallery"),
          $galleryImg = $("#galleryImg"),
          $uploaderInput =   $("#uploaderInput"),
          $uploaderFiles = $("#uploaderFiles");

      $uploaderInput.on("change", function (e) {
            files = e.target.files;
            // 如果没有选中文件，直接返回
            if (files.length === 0) {
                return;
            }
            for (var i = 0, len = files.length; i < len; ++i) {
                var file = files[i];
                var imgID = genGUID();
                var reader = new FileReader();
                var fileType = file.type;
                // 如果类型不在允许的类型范围内
                if (allowTypes.indexOf(file.type) === -1) {
                    layer.msg('该类型不允许上传' + fileType);
                    continue;
                }

                if (file.size > maxSize) {
                    layer.msg("图片太大，不允许上传");
                    continue;
                }

                if ($('.weui-uploader__file').length >= maxCount) {
                    layer.msg('最多只能上传' + maxCount + '张图片');
                    return;
                }

                uploadFileList.push(file);

                reader.onload = function (e) {
                    var img = new Image();
                    img.onload = function () {
                        // 不要超出最大宽度
                        var w = Math.min(maxWidth, img.width);
                        // 高度按比例计算
                        var h = img.height * (w / img.width);
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        // 设置 canvas 的宽度和高度
                        canvas.width = w;
                        canvas.height = h;
                        ctx.drawImage(img, 0, 0, w, h);
                        var base64 = canvas.toDataURL(fileType,0.6); //0.6指的是压缩60%

                        // 插入到预览区
                        $uploaderFiles.append($(tmpl.replace('#url#', base64).replace('#ImgID#', imgID)));

                        var num = $('.weui-uploader__file').length;
                        $('#uploadCount').text(num);

                        function uploading() {

                            $uploaderFiles.find('.weui-uploader__file').removeClass('weui-uploader__file_status');
                            $uploaderFiles.find('.weui-uploader__file-content').remove();//清除上传进度图标
                        }
                        setTimeout(uploading, 1000);
                    };

                    img.src = e.target.result;


                };
                reader.readAsDataURL(file);

            }
        });

      var index,attid; //第几张图片
        $uploaderFiles.on("click", "li", function () {
            index = $(this).index();
            attid = $(this).data('attid');
            $galleryImg.attr("style", this.getAttribute("style"));
            $gallery.fadeIn(100);
        });
        $gallery.on("click", function () {
            $gallery.fadeOut(100);
        });

        //删除图片
        $(".weui-gallery__del").on("click", function () {

            var uri = "{{route('wx.my.attachment.remove')}}";

            $.post(uri, {
                '_token': $("input[name='_token']").attr('value'),
                'tuser': $("input[name='tuser']").val(),
                'attid': attid,
                'is_submit': true
            }, function (data) {
                layer.msg(data.message, {time: 1000, shift: -1}, function () {

                    $uploaderFiles.find("li").eq(index).remove();
                    uploadFileList.splice(index,1);
                    var num = $('.weui-uploader__file').length;
                    $('#uploadCount').text(num);

                    if (data.status === true && data.url != null) {
                        $(window).attr('location', data.url);
                    }
                });

            }, 'json').error(function (data) {
                layer.msg(data.responseJSON.message);
            });

        });

      function genGUID() {
        var G1 = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        var G2 = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        return (G1 + G2);
    }


      $('.swiper-container').swiper({
        loop: true,
        autoplay: 5000,
        pagination: '.swiper-pagination',
        paginationClickable: true
      });


      $('#btnCancel').on('click', function () {

          var uri = "{{route('wx.my.cancel')}}";

          layer.msg('确认取消报名？',{
            time: 0,
            btn: ['确定', '取消'],
            yes: function(index) {
              $.post(uri, {
                '_token': $("input[name='_token']").attr('value'),
                  'tuser': $("input[name='tuser']").val(),
                  'is_submit': true
              }, function (data) {
                  layer.msg(data.message, {time: 1000, shift: -1}, function () {
                      if (data.status === true && data.url != null) {
                          $(window).attr('location', data.url);
                      }
                  });

              }, 'json').error(function (data) {
                  layer.msg(data.responseJSON.message);
              });
            }
          });


      });


  });
  </script>
@stop